import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import { prisma } from "@/lib/prisma";
import { writeFile } from "fs/promises";
import { join } from "path";
import { isSupportedFileType, formatFileSize } from "@/lib/utils";
import { MAX_FILE_SIZE } from "@/lib/constants";

// 获取知识库的所有文档
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;
    const { searchParams } = new URL(req.url);
    
    // 检查知识库是否存在
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此知识库" },
        { status: 403 }
      );
    }

    // 获取查询参数
    const search = searchParams.get("search") || "";

    // 查询文档
    const documents = await prisma.document.findMany({
      where: {
        knowledgeBaseId: id,
        name: {
          contains: search,
          mode: "insensitive" as const,
        },
      },
      orderBy: { createdAt: "desc" },
    });

    return NextResponse.json({
      success: true,
      data: documents,
    });
  } catch (error) {
    console.error("获取文档失败:", error);
    return NextResponse.json(
      { success: false, error: "获取文档失败" },
      { status: 500 }
    );
  }
}

// 上传文档
export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;

    // 检查知识库是否存在
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此知识库" },
        { status: 403 }
      );
    }

    // 处理文件上传
    const formData = await req.formData();
    const file = formData.get("file") as File | null;

    if (!file) {
      return NextResponse.json(
        { success: false, error: "未提供文件" },
        { status: 400 }
      );
    }

    // 验证文件类型
    if (!isSupportedFileType(file.name)) {
      return NextResponse.json(
        { success: false, error: "不支持的文件类型" },
        { status: 400 }
      );
    }

    // 验证文件大小
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { 
          success: false, 
          error: `文件过大，最大允许大小: ${formatFileSize(MAX_FILE_SIZE)}` 
        },
        { status: 400 }
      );
    }

    // 读取文件内容
    const fileContent = await file.text();
    
    // 获取文件扩展名
    const fileExtension = file.name.split(".").pop() || "";

    // 创建文档记录
    const document = await prisma.document.create({
      data: {
        name: file.name,
        content: fileContent,
        fileType: fileExtension,
        fileSize: file.size,
        knowledgeBaseId: id,
      },
    });

    // 这里应该添加向量化处理，但需要实际LLM API集成
    // 在实际项目中，这里会将文档内容分段，并使用嵌入模型创建向量表示

    return NextResponse.json({
      success: true,
      data: document,
    });
  } catch (error) {
    console.error("上传文档失败:", error);
    return NextResponse.json(
      { success: false, error: "上传文档失败" },
      { status: 500 }
    );
  }
} 